package de.slothsoft.commons.swing.validation;

import java.text.MessageFormat;

import javax.swing.text.JTextComponent;

import de.slothsoft.commons.StringParser;
import de.slothsoft.commons.res.CommonMessages;

public class ReturnTypeTester<S extends JTextComponent> implements ITester<S> {

	private Class<?> returnType;

	public ReturnTypeTester(Class<?> returnType) {
		this.returnType = returnType;
	}

	@Override
	public boolean acceptInput(JTextComponent source) {
		String text = source.getText();
		if (text == null || text.trim().isEmpty())
			return true; // tested by the mandatory tester
		try {
			StringParser.parse(text.trim(), this.returnType);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public String getErrorMessage(String sourceName) {
		return MessageFormat.format(
				CommonMessages.getString("Validator.wrongFormat"), sourceName);
	}

}
